import {
  getCardList
} from "../../apis/card";
import {
  getGroupDetails,
  addGroup,
  addGroupCard,
  removeGroupCard
} from "../../apis/group";
import {
  getLabelDetails,
  addLabel,
  addLabelcard,
  removeLabelCard
} from "../../apis/label"
const app = getApp();

Page({
  data: {
    label: null,
    headTop: null,
    headHeight: null,
    stickyTop: null,
    type: null,
    groupId: null,
    rankList: [],
    indexList: [],
    selectList: [],
    newCardId: []
  },

  onLoad(options) {
    let menu = wx.getMenuButtonBoundingClientRect();
    this.setData({
      headTop: menu.top + 2,
      headHeight: menu.height,
      ...options
    });
    if (options.type === 'create') {
      this.getMailList();
    } else if (options.type === 'add') {
      if (options.from === 'group') this.getGroupMember(options.groupId);
      if (options.from === 'label') this.getLabelMember(options.labelId);
    } else if (options.type === 'delete') {
      if (options.from === 'group') this.getGroupMember(options.groupId);
      if (options.from === 'label') this.getLabelMember(options.labelId);
    };
  },

  onReady() {
    let query = wx.createSelectorQuery();
    query.select('.fxd').boundingClientRect(rect => {
      this.setData({
        stickyTop: rect.height
      });
    }).exec();
  },

  // 获取名片
  getMailList() {
    getCardList({
      status: 1,
      cardType: 2
    }).then(res => {
      if (res.data.code === 200) {
        let {
          rows
        } = res.data;
        let indexList = [];
        rows.forEach(v => {
          v.select = false;
          v.click = false;
          if (this.data.type === 'add') {
            this.data.selectList.forEach(val => {
              if (v.cardId === val.cardId) {
                v.select = true;
                v.click = true;
              }
            })
          }
          indexList.push(v.userName.substr(0, 1).spell('first'));
        });
        indexList = [...new Set(indexList.sort())];
        let rankList = indexList.map(v => {
          return {
            rank: v,
            cardList: []
          }
        });
        rows.forEach(v => {
          rankList.forEach(val => {
            if (v.userName.substr(0, 1).spell('first') === val.rank) {
              if (v.imageList) {
                v.imageList = v.imageList.map(v => {
                  return v = !new RegExp('^https://').test(v) && !new RegExp('^http://').test(v) ? app.globalData.url + v : v;
                });
              };
              v.avatar = !new RegExp('^https://').test(v.avatar) && !new RegExp('^http://').test(v.avatar) ? app.globalData.url + v.avatar : v.avatar;
              val.cardList.push(v);
            };
          });
        });
        this.setData({
          rankList: rankList,
          indexList: indexList
        });

        setTimeout(() => {
          this.getRankTop();
        }, 500);
      };
    });
  },

  getRankTop() {
    let query = wx.createSelectorQuery();
    this.data.indexList.forEach(v => {
      query.select('#jump' + v).boundingClientRect();
    });
    query.exec(v => {
      console.log(v);
      this.setData({
        indexList: v
      });
    });
  },

  // 页面滚动
  jumpRank(e) {
    let {
      rank
    } = e.currentTarget.dataset;
    let query = wx.createSelectorQuery();
    query.select('.fxd').boundingClientRect(rect => {
      this.data.indexList.forEach(v => {
        if ('jump' + rank === v.id) {
          wx.pageScrollTo({
            duration: 300,
            scrollTop: v.top - rect.height
          });
        };
      });
    }).exec();
  },

  // 当添加新成员或删除成员时获取当前组人员信息
  getGroupMember(id) {
    getGroupDetails(id).then(res => {
      if (res.data.code === 200) {
        let {
          data
        } = res.data;
        data.groupCardList.forEach(v => {
          if (!new RegExp('^https://').test(v.avatar) && !new RegExp('^http://').test(v.avatar)) v.avatar = app.globalData.url + v.avatar;
        });
        if (this.data.type === 'add') {
          data.groupCardList.map(v => {
            return v.select = true
          });
          this.setData({
            selectList: data.groupCardList
          });
          this.getMailList();
        } else if (this.data.type === 'delete') {
          this.setData({
            rankList: data.groupCardList
          });
        }
      };
    });
  },
  getLabelMember(id) {
    getLabelDetails(id).then(res => {
      if (res.data.code === 200) {
        let {
          data
        } = res.data;
        data.labelCardList.forEach(v => {
          if (!new RegExp('https://').test(v.avatar) && !new RegExp('http://').test(v.avatar)) v.avatar = app.globalData.url + v.avatar;
        });
        if (this.data.type === 'add') {
          data.labelCardList.map(v => {
            return v.select = true
          });
          this.setData({
            selectList: data.labelCardList
          });
          this.getMailList();
        } else if (this.data.type === 'delete') {
          this.setData({
            rankList: data.labelCardList
          });
        };
      };
    });
  },

  // 选人
  handleSelect(e) {
    let {
      id
    } = e.currentTarget.dataset;
    let arr1 = this.data.rankList;
    let arr2 = this.data.selectList;
    let arr3 = this.data.newCardId;
    if (this.data.type === 'delete') {
      arr1.forEach(v => {
        if (v.cardId === id) {
          v.select = !v.select;
          if (v.select) {
            arr2.unshift(v);
          } else {
            arr2.splice(arr2.indexOf(v), 1);
          }
        }
      });
      this.setData({
        rankList: arr1,
        selectList: arr2
      })
    } else {
      arr1.forEach(v => {
        v.cardList.forEach(val => {
          if (val.cardId === id) {
            val.select = !val.select
            if (val.select) {
              arr2.unshift(val);
              arr3.unshift(id);
            } else {
              arr2.splice(arr2.indexOf(val), 1);
              arr3.splice(arr3.indexOf(id), 1);
            }
          };
        });
      });
      this.setData({
        rankList: arr1,
        selectList: arr2,
        newCardId: arr3
      });
    };
  },

  // 完成
  handleCreate() {
    if (this.data.from === 'group' && this.data.type === 'add') {
      this.addNewMember();
    } else if (this.data.from === 'group' && this.data.type === 'create') {
      this.createGroup();
    } else if (this.data.from === 'group' && this.data.type === 'delete') {
      this.deleteMomber();
    } else if (this.data.from === 'label' && this.data.type === 'add') {
      this.addLabelMember();
    } else if (this.data.from === 'label' && this.data.type === 'create') {
      this.createLabel();
    } else if (this.data.from === 'label' && this.data.type === 'delete') {
      this.deleteLabelMomber();
    }
  },

  // 群组添加新成员
  addNewMember() {
    if (this.data.newCardId.length === 0) {
      wx.navigateBack({
        delta: 1,
      });
    } else {
      wx.showModal({
        title: '添加成员',
        content: '确定添加新成员吗？',
        success: res => {
          if (res.confirm) {
            addGroupCard(this.data.groupId, this.data.newCardId).then(res => {
              if (res.data.code === 200) {
                wx.showToast({
                  title: '添加成功',
                  icon: 'success',
                  mask: true,
                  duration: 1500,
                  success: res => {
                    let timer = setTimeout(() => {
                      wx.navigateBack({
                        delta: 1
                      });
                      clearTimeout(timer);
                    }, 1500);
                  }
                });
              };
            });
          };
        }
      });
    };
  },

  // 创建新群组
  createGroup() {
    let arr = [];
    arr = this.data.selectList.map(v => {
      return v.cardId
    });
    wx.showModal({
      title: '创建名片组',
      content: '确定创建名片组吗？',
      success: res => {
        if (res.confirm) {
          addGroup('未命名群组', arr).then(res => {
            if (res.data.code === 200) {
              wx.showToast({
                title: '创建成功',
                icon: 'success',
                mask: true,
                duration: 1500,
                success: res => {
                  let timer = setTimeout(() => {
                    wx.navigateBack({
                      delta: 1
                    });
                    clearTimeout(timer);
                  }, 1500);
                }
              });
            };
          });
        };
      }
    });
  },

  // 群组删除成员
  deleteMomber() {
    let arr = [];
    this.data.selectList.forEach(v => {
      if (v.select) {
        arr.push(v.cardId)
      };
    });
    wx.showModal({
      title: '删除成员',
      content: '确定删除这些成员吗？',
      success: res => {
        if (res.confirm) {
          removeGroupCard(this.data.groupId, arr).then(res => {
            if (res.data.code === 200) {
              wx.showToast({
                title: '删除成功',
                icon: 'success',
                mask: true,
                duration: 1500,
                success: res => {
                  let timer = setTimeout(() => {
                    wx.navigateBack({
                      delta: 1
                    });
                    clearTimeout(timer);
                  }, 1500);
                }
              });
            };
          });
        };
      }
    });
  },

  // 标签添加新成员
  addLabelMember() {
    if (this.data.newCardId.length === 0) {
      wx.navigateBack({
        delta: 1,
      });
    } else {
      wx.showModal({
        title: '添加成员',
        content: '确定添加新成员吗？',
        success: res => {
          if (res.confirm) {
            addLabelcard(this.data.labelId, this.data.newCardId).then(res => {
              if (res.data.code === 200) {
                wx.showToast({
                  title: '添加成功',
                  icon: 'success',
                  mask: true,
                  duration: 1500,
                  success: res => {
                    let timer = setTimeout(() => {
                      wx.navigateBack({
                        delta: 1
                      });
                      clearTimeout(timer);
                    }, 1500);
                  }
                });
              };
            });
          };
        }
      });
    };
  },

  // 创建新标签
  createLabel() {
    let arr = [];
    arr = this.data.selectList.map(v => {
      return v.cardId
    });
    wx.showModal({
      title: '创建标签',
      content: '确定创建标签吗？',
      success: res => {
        if (res.confirm) {
          addLabel(this.data.label, arr).then(res => {
            if (res.data.code === 200) {
              wx.navigateBack({
                delta: 1
              });
            };
          });
        };
      }
    });
  },

  // 标签删除成员
  deleteLabelMomber() {
    let arr = [];
    this.data.selectList.forEach(v => {
      if (v.select) {
        arr.push(v.cardId)
      };
    });
    wx.showModal({
      title: '删除成员',
      content: '确定删除这些成员吗？',
      success: res => {
        if (res.confirm) {
          removeLabelCard(this.data.labelId, arr).then(res => {
            if (res.data.code === 200) {
              wx.showToast({
                title: '删除成功',
                icon: 'success',
                mask: true,
                duration: 1500,
                success: res => {
                  let timer = setTimeout(() => {
                    wx.navigateBack({
                      delta: 1
                    });
                    clearTimeout(timer);
                  }, 1500);
                }
              });
            };
          });
        };
      }
    });
  },

  goback() {
    wx.navigateBack({
      delta: 1,
    })
  }
})